package com.wtwd.campus.controller;

import com.alibaba.fastjson.JSONObject;
import com.wtwd.campus.annotation.AuditLog;
import com.wtwd.campus.common.Constants;
import com.wtwd.campus.common.RespCode;
import com.wtwd.campus.common.RespEntity;
import com.wtwd.campus.constant.SignConstant;
import com.wtwd.campus.entity.*;
import com.wtwd.campus.service.*;
import com.wtwd.campus.thread.ForkJoinPushTask;
import com.wtwd.campus.utils.AuditLogUtils;
import com.wtwd.campus.utils.ForkJoinPoolUtils;
import com.wtwd.campus.wx.service.WxUtilsService;
import org.apache.commons.lang.StringUtils;
import org.jeewx.api.core.req.model.message.TemplateMessageSendResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.*;

@RestController
@RequestMapping("/message")
public class MessageController {
    private final static Logger logger = LoggerFactory.getLogger(MessageController.class);


    @Autowired
    private RedisService redisService;
    @Autowired
    private LogService logService;
    @Autowired
    private InformationService informationService;
    @Autowired
    private NotificationService notificationService;
    @Autowired
    private SchoolService schoolService;
    @Autowired
    private ClassService classService;
    @Autowired
    private WxService wxService;
    @Autowired
    private WarningRecordService warningRecordService;

    @Autowired
    private WxUtilsService wxUtilsService;


    @Value("${wx.general.push.customerCode}")
    private String wxPushCustomerCode;


    /**
     * 条件查询资讯列表信息
     *
     * @param data
     * @return
     */
    @PostMapping("/getInformationList")
    public RespEntity getInformationList(@RequestBody InformationVO data) {
        logger.info("/getInformationList:data={}", data.toString());
        //根据条件获取资讯列表
        Map<String, Object> list = informationService.getInformationListByCondition(data);
        return new RespEntity(RespCode.SUCCESS, list);
    }

    /**
     * 根据id获取资讯信息
     *
     * @param id
     * @return
     */
    @GetMapping("/getInformationById/{id}")
    public RespEntity getInformationById(@PathVariable Integer id) {
        logger.info("/getInformationById:id={}", id.toString());
        //根据id获取资讯信息
        Information information = informationService.getInformationById(id);
        /*  information.setContent(information.getContent().replace("<br/>"," "));*/
        if (information == null) {
            return new RespEntity(RespCode.NO_DATA);
        }
        return new RespEntity(RespCode.SUCCESS, information);

    }

    /**
     * 发布资讯
     *
     * @param data
     * @param request
     * @return
     */
    @PostMapping("/addInformation")
    @AuditLog(operationType = "发布资讯", operationContent = "", orgCode = "")
    @Transactional
    public RespEntity addInformation(@RequestBody Information data, HttpServletRequest request) {
        logger.info("/addInformation:data={}", data.toString());
        /*data.setContent(data.getContent().replace("\n","<br/>"));*/
        JSONObject userInfo = getUserInfo(request);
        if (userInfo == null || userInfo.getInteger("userId") == null) {
            return new RespEntity(RespCode.USER_INDEX_EXPIRE);
        }
        School schoolInfo = schoolService.getSchoolInfoById(data.getSchoolId());
        if (schoolInfo == null) {
            return new RespEntity(RespCode.SCHOOL_NOT_EXIST);
        }
        Integer userId = userInfo.getInteger("userId");
        String account = userInfo.getString("account");
        data.setCreateTime(System.currentTimeMillis());
        data.setUserId(userId);
        data.setUserName(account);
        //新增一笔资讯
        int i = informationService.addInformation(data);
        //修改注释信息
        if (i > 0) {
            Method method = null;
            try {
                method = MessageController.class.getMethod("addInformation", Information.class, HttpServletRequest.class);
                //根据学校id获取学校名称
                School school = logService.getSchoolById(data.getSchoolId());
                //获取操作的组织id
                String orgCode = school.getOrgCode();
                String operationContent = "对".concat(school.getSchoolName()).concat("发布资讯");
                AuditLogUtils.modifyAnnotation(method, operationContent, orgCode);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
        if (i > 0) {
            //开线程去进行微信推送
            //获取需要推送的openId集合
            List<String> openIdList = wxService.getOpenIdListBySchoolId(data.getSchoolId());
            if (openIdList.size() > 0) {
                List<String> openIdList2 = new ArrayList<>();
                openIdList.stream().forEach(e -> {
                    if (!StringUtils.isBlank(e)) {
                        openIdList2.add(e);
                    }
                });
                PushMessDataVO pushMessDataVO = new PushMessDataVO();
                pushMessDataVO.setOpenIdList(openIdList2);
                pushMessDataVO.setFlag(Constants.PUSH_INFORMATION);
                pushMessDataVO.setContent(data.getContent());
                pushMessDataVO.setId(data.getId());
                pushMessDataVO.setType(data.getType());
                pushMessDataVO.setSchoolId(data.getSchoolId());
                pushMessDataVO.setTitle(data.getTitle());
                pushMessDataVO.setUserName(data.getUserName());
                pushMessDataVO.setSchoolName(schoolInfo.getSchoolName());
                logger.info("推送的内容为：data={}", pushMessDataVO.toString());
                //进行微信推送
                if (StringUtils.isNotBlank(wxPushCustomerCode)&&StringUtils.isNotBlank(schoolInfo.getOrgCode())){
                    List<String> customerCodeString = Arrays.asList(wxPushCustomerCode.split(SignConstant.COMMA));
                    String pushCode = wxUtilsService.getWxCustomerCode(customerCodeString, schoolInfo.getOrgCode());
                    if (StringUtils.isNotBlank(pushCode)){
                        ForkJoinPushTask task = new ForkJoinPushTask(pushCode,wxUtilsService,pushMessDataVO, openIdList2, 0);
                        ForkJoinPoolUtils.forkJoinPool.execute(task);
                        return new RespEntity(i > 0 ? RespCode.SUCCESS : RespCode.FAILED);
                    }
                }
                ForkJoinPushTask task = new ForkJoinPushTask(pushMessDataVO, openIdList2, 0);
                ForkJoinPoolUtils.forkJoinPool.execute(task);
            }
        }
        return new RespEntity(i > 0 ? RespCode.SUCCESS : RespCode.FAILED);
    }


    /**
     * 条件查询通知列表信息
     *
     * @param data
     * @return
     */
    @PostMapping("/getNotificationList")
    public RespEntity getNotificationList(@RequestBody NotificationVO data) {
        logger.info("/getNotificationList:data={}", data.toString());
        //根据条件获取通知列表
        Map<String, Object> list = notificationService.getNotificationByCondition(data);
        return new RespEntity(RespCode.SUCCESS, list);
    }


    /**
     * 根据id获取通知信息
     *
     * @param id
     * @return
     */
    @GetMapping("/getNotificationById/{id}")
    public RespEntity getNotificationById(@PathVariable Integer id) {
        logger.info("/getNotificationById:id={}", id.toString());
        //根据id获取资讯信息
        Notification notification = notificationService.getNotificationById(id);
        /*notification.setContent(notification.getContent().replace("<br/>"," "));*/
        if (notification == null) {
            return new RespEntity(RespCode.NO_DATA);
        }
        return new RespEntity(RespCode.SUCCESS, notification);
    }


    /**
     * 发布通知
     *
     * @param data
     * @param request
     * @return
     */
    @PostMapping("/addNotification")
    @AuditLog(operationType = "发布通知", operationContent = "", orgCode = "")
    @Transactional
    public RespEntity addNotification(@RequestBody Notification data, HttpServletRequest request) {
        logger.info("/addNotification:data={}", data.toString());
        /* String content = data.getContent();*/
        JSONObject userInfo = getUserInfo(request);
        if (userInfo == null || userInfo.getInteger("userId") == null) {
            return new RespEntity(RespCode.USER_INDEX_EXPIRE);
        }
        //判断班级是否存在
        Integer classesId = classService.getClassIdByClassId(data.getClassId());
        if (classesId == null) {
            return new RespEntity(RespCode.CLASS_NOT_EXIST);
        }
        Integer userId = userInfo.getInteger("userId");
        String account = userInfo.getString("account");
        data.setCreateTime(System.currentTimeMillis());
        data.setUserId(userId);
        data.setUserName(account);
        //根据班级id查找年级学校信息
        Map<String, Object> map = notificationService.getSchoolAndGradeMessByClassId(data.getClassId());
        data.setClassName((String) map.get("classes_name"));
        data.setGradeId((Integer) map.get("grade_id"));
        data.setGradeName((String) map.get("grade_name"));
        data.setSchoolId((Integer) map.get("school_id"));
        //新增一笔通知
        /*String saveContent = content.replace("\n", "<br/>");
        data.setContent(saveContent);*/
        int i = notificationService.addNotification(data);
        //修改注释信息
        if (i > 0) {
            Method method = null;
            try {
                method = MessageController.class.getMethod("addNotification", Notification.class, HttpServletRequest.class);
                //获取操作的组织id
                String orgCode = logService.getOrgCodeBySchoolId((Integer) map.get("school_id"));
                String operationContent = "对".concat((String) map.get("classes_name")).concat("发布通知");
                AuditLogUtils.modifyAnnotation(method, operationContent, orgCode);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
        if (i > 0) {
            //获取需要推送的openId集合
            List<Map<String, Object>> messList = wxService.getOpenIdAndStuNameListByClassId(classesId);
            List<String> listStr = new ArrayList<>();
            messList.stream().forEach(e -> {
                if (!StringUtils.isBlank((String) e.get("open_id"))) {
                    String openId = (String) e.get("open_id");
                    String stuName = (String) e.get("student_name");
                    listStr.add(openId.concat(",").concat(stuName == null ? "" : stuName));
                }
            });
            PushMessDataVO pushMessDataVO = new PushMessDataVO();
            pushMessDataVO.setFlag(Constants.PUSH_NOTIFICATION);
            pushMessDataVO.setClassName(data.getGradeName().concat(data.getClassName()));
            pushMessDataVO.setContent(data.getContent());
            pushMessDataVO.setId(data.getId());
            pushMessDataVO.setTitle(data.getTitle());
            pushMessDataVO.setUserName(data.getUserName());
            pushMessDataVO.setTime(System.currentTimeMillis());
            logger.info("推送通知内容为：data={}", pushMessDataVO.toString());
            //进行微信推送
            ForkJoinPushTask task = new ForkJoinPushTask(pushMessDataVO, listStr, 0);
            ForkJoinPoolUtils.forkJoinPool.execute(task);
            //根据班级id获取一个班级的imei
            List<String> imeiList = classService.getImeiListByClassId(classesId);
            PushMessDataVO pushDeviceTask = new PushMessDataVO();
            pushDeviceTask.setTitle(data.getTitle());
            pushDeviceTask.setContent(data.getContent());
            pushDeviceTask.setId(data.getId());
            pushDeviceTask.setUserId(userId);
            ForkJoinPushTask task2 = new ForkJoinPushTask(pushDeviceTask, imeiList, 1);
            ForkJoinPoolUtils.forkJoinPool.execute(task2);
        }
        return new RespEntity(i > 0 ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 获取未读信息
     *
     * @return
     */
    @GetMapping("/getUnReadMess")
    public RespEntity getUnReadMess() {
        logger.info("/getUnReadMess");
        List<OrgExpiration> unReadOrgExpirationMess = warningRecordService.getUnReadOrgExpirationMess();
        //将数据库的未读消息都变成已读
        warningRecordService.updateIfRead();
        return new RespEntity(RespCode.SUCCESS, unReadOrgExpirationMess);

    }

    /**
     * 获取未读信息条数
     *
     * @return
     */
    @GetMapping("/getUnReadMessCount")
    public RespEntity getUnReadMessCount() {
        logger.info("/getUnReadMessCount");
        Integer count = warningRecordService.getUnReadCount();
        Map<String, Object> result = new HashMap<>();
        if (count == 0) {
            result.put("number", "");
        }
        return new RespEntity(RespCode.SUCCESS, result);

    }


    /**
     * 获取全部消息
     *
     * @return
     */
    @PostMapping("/getAllExpirationMess")
    public RespEntity getAllExpirationMess(@RequestBody JSONObject data) {
        logger.info("/getAllExpirationMess:data={}", data.toString());
        Integer curPage = data.getInteger("curPage");
        Integer pageSize = data.getInteger("pageSize");
        Map<String, Object> result = warningRecordService.queryOrgExpirationByPage(curPage, pageSize);
        return new RespEntity(RespCode.SUCCESS, result);

    }


    /**
     * 获取用户信息
     *
     * @param request
     * @return
     */
    public JSONObject getUserInfo(HttpServletRequest request) {
        //获取用户的组织编号
        String token = request.getHeader(Constants.HEADER_TOKEN_KEY);
        Map<String, Object> msg = redisService.getUserInfoByToken(token);
        String userMsg = (String) msg.get("user");
        JSONObject jsonObject = JSONObject.parseObject(userMsg);
        return jsonObject;
    }





 /*   @GetMapping("/testA")
    public RespEntity testA() {
        List<String> list=new ArrayList<>();
        for (int i=0;i<100;i++){
            list.add(String.valueOf(i));
        }
        PushMessDataVO pushMessDataVO=new PushMessDataVO();
        pushMessDataVO.setOpenIdList(list);
        pushMessDataVO.setFlag(1);
        pushMessDataVO.setSchoolId(2);
        pushMessDataVO.setContent("测试资讯");
        pushMessDataVO.setId(1);
        pushMessDataVO.setTitle("测试标题");
        pushMessDataVO.setType(2);
        pushMessDataVO.setUserName("px");
        ForkJoinPushTask task=new ForkJoinPushTask(pushMessDataVO,list);
     *//*   ForkJoinPool pool=new ForkJoinPool(4,new ThrowsExceptionThreadFactory(),new ForkJoinPoolExceptionHandler(),false);*//*
        forkJoinPool.execute(task);
        try {
            Thread.sleep(15000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(listA.toString());
        return new RespEntity(RespCode.SUCCESS);
    }*/

}
